package com.mcxx.modules.temporary.controller;

import com.mcxx.modules.temporary.service.TempNoticeBoardService;
import com.mcxx.modules.miniSalvation.order.dto.NoticeBoardDTO;
import com.mcxx.modules.miniSalvation.order.entity.NoticeBoardDetailEntity;
import com.mcxx.modules.miniSalvation.order.param.NoticeBoardParam;
import com.mcxx.modules.miniSalvation.order.param.NoticeBoardSearchOrderParam;
import com.mcxx.modules.miniSalvation.order.param.OrderListSearchParam;
import com.mcxx.modules.miniSalvation.order.service.read.NoticeBoardDetailReadService;
import com.mcxx.modules.miniSalvation.order.service.read.NoticeBoardReadService;
import com.mcxx.modules.miniSalvation.order.service.write.NoticeBoardDetailWriteService;
import com.mcxx.result.BaseResult;
import com.mcxx.service.DefaultRestService;
import com.mcxx.util.Constant;
import com.mcxx.util.ZipInfoUtil;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.restservice.annotation.RestService;
import com.yinhai.ta404.core.restservice.requestbean.PageParam;
import com.yinhai.ta404.core.restservice.resultbean.Page;
import com.yinhai.ta404.core.validate.annotation.V;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;


@Validated
@Api("临时救助/公示")
@RestService({"temporary/noticeboard/v2"})
public class TempNoticeBoardController extends DefaultRestService {

    private final static Logger log = LoggerFactory.getLogger(TempNoticeBoardController.class);

    @Autowired
    private NoticeBoardReadService noticeBoardReadService;
    @Autowired
    private TempNoticeBoardService tempNoticeBoardService;
    @Autowired
    private NoticeBoardDetailReadService noticeBoardDetailReadService;
    @Autowired
    private NoticeBoardDetailWriteService noticeBoardDetailWriteService;


    @PostMapping("findList")
    @ApiOperation(value="公示列表页", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="公示列表页")
    public void findList(NoticeBoardParam param, PageParam pageParam){
        log.info("公示列表页查询开始，参数是：{}", param);
        param.setBusinessType(Constant.BusinessCode.LINSHI);
        param.setUserAreaLevel(getCurUserAccount().getAreaLevel());
        param.setTableOrder("BCX56");
        Page page = noticeBoardReadService.findPage(param,pageParam, getCurUserAccount());
        this.setPageBean(page);
        log.info("查询公示列表页查询结束，结果是：{}", page);
    }


    @PostMapping("save")
    @ApiOperation(value="添加公示批次", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="添加公示批次")
    public void save(NoticeBoardDTO noticeBoard){
        log.info("开始添加公示批次，参数是：{}", noticeBoard);
        noticeBoard.setBusinessType(Constant.BusinessCode.LINSHI);
        String batchId = "";
        if(null != noticeBoard.getBatchId()){
            batchId = noticeBoard.getBatchId();
        }else{
            batchId = Constant.getUUID();
        }
        noticeBoard.setBatchId(batchId);
        noticeBoard.setAddressCode(noticeBoard.getAreaCode());
        noticeBoard.setAreaCode(noticeBoard.getAreaCode());
        if(null == noticeBoard.getAreaCode()){
            noticeBoard.setAddressCode(getCurUserAccount().getAreaCode());
            noticeBoard.setAreaCode(getCurUserAccount().getAreaCode());
        }
        boolean rst = tempNoticeBoardService.changeDtoToEntity(noticeBoard, getCurUserAccount());
        setData("data", rst);
        log.info("公示批次添加结束，结果是：{}", rst);
    }


    @PostMapping("changeMember")
    @ApiOperation(value="根据发放类型获取未进入公式的成员信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="添加公示批次")
    public void changeMember(@V("notnull") NoticeBoardDTO noticeBoard){
        log.info("开始添加公示批次，参数是：{}", noticeBoard);
        BaseResult re = new BaseResult();
        NoticeBoardSearchOrderParam param = new NoticeBoardSearchOrderParam();
        String batchId = "";
        if(StringUtils.isNotBlank(noticeBoard.getBatchId())){
            batchId = noticeBoard.getBatchId();
        }else{
            batchId = Constant.getUUID();
        }
        param.setAreaCode(noticeBoard.getAreaCode());
        param.setBusinessType(Constant.BusinessCode.LINSHI);
        param.setName(noticeBoard.getName());
        param.setIdcard(noticeBoard.getIdcard());
        param.setBatchId(batchId);
        param.setBatchNo(getCurUserAccount().getAreaLevel());
        param.setPayWay(noticeBoard.getPayWay());

        Object o = noticeBoardReadService.queryNoFormulaList(param, getCurUserAccount(), 1);
        re.setData(o);
        re.setMsg(batchId);
        setData("data", re);
        log.info("公示批次添加结束，结果是：{}", batchId);
    }


    @PostMapping("findSaveObject")
    @ApiOperation(value="查询指定批次中的公示对象", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="查询指定批次中的公示对象-乡镇")
    public void findSaveObject(OrderListSearchParam param, PageParam pageParam){
        log.info("开始查询指定批次中的公示对象，参数是：{}", param);
        param.setBusinessType(Constant.BusinessCode.LINSHI);
        param.setTableOrder("BCX56");
        param.setTableFamily("BCF13");
        Page page = noticeBoardDetailReadService.findSaveObject(param, pageParam,getCurUserAccount());
        this.setPageBean(page);
        log.info("开始查询指定批次中的公示对象，查询结果是：{}", page);

    }


    @PostMapping("downLoadNoticeMemberList")
    @ApiOperation(value="查询指定批次中的公示对象", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="查询指定批次中的公示对象-乡镇")
    public void downLoadNoticeMemberList(HttpServletResponse response, @RequestBody OrderListSearchParam param)throws IOException {
        log.info("开始查询指定批次中的公示对象，参数是：{}", param);
        param.setBusinessType(Constant.BusinessCode.LINSHI);
        param.setTableOrder("BCX56");
        param.setTableFamily("BCF13");
        ExcelInfo excelInfo = noticeBoardDetailWriteService.exportExcelNoticeMember(param,getCurUserAccount());
        if(null != excelInfo){
            ZipInfoUtil.exportZipResponse(response, excelInfo, this.getCurUserId());
        }
        log.info("开始查询指定批次中的公示对象，查询结果是：{}", excelInfo);

    }


    @PostMapping("deleteBatch")
    @ApiOperation(value="删除公示批次", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="删除公示批次")
    public void deleteBatch(@RequestPart @V("notnull") List<String> batchNoList){
        log.info("开始删除公示批次，参数是：{}", batchNoList);
        Map<String, List<String>> rstMap = tempNoticeBoardService.deleteBatch(batchNoList, getCurUserAccount());
        setData(packageRstMsg(rstMap));
        log.info("删除公示批次，结果是：{}", rstMap);
    }


    @PostMapping("confirmBatch")
    @ApiOperation(value="确认公示", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="确认公示")
    public void confirmBatch(@RequestPart @V("notnull") List<String> batchNoList){
        log.info("开始确认公示，参数是：{}", batchNoList);
        Map<String, List<String>> rstMap = tempNoticeBoardService.confirmBatch(batchNoList, getCurUserAccount().getAreaLevel());
        setData(packageRstMsg(rstMap));
        log.info("确认公示结束，结果是：{}", rstMap);
    }


    @PostMapping("finishBatch")
    @ApiOperation(value="结束批次", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="结束批次")
    public void finishBatch(@RequestPart @V("notnull") List<NoticeBoardDetailEntity> changeData, String batchId,
                            String operatType, String finishRemark){
        log.info("结束公示结束，批次号是：{}", changeData);


        if("1".equals(operatType)){
            if(CollectionUtils.isNotEmpty(changeData)){
                int i = noticeBoardDetailWriteService.updateBatchId(changeData);
                if (i >= 0){
                    setData(true);
                }else{
                    setData(false);
                }
            }else{
                setData(true);
            }
        }else{
            tempNoticeBoardService.sendRabbitMQToFinish(changeData, batchId, finishRemark, getCurUserAccount());
            setData(true);
        }
    }


    @PostMapping("findEntrustTodo")
    @ApiOperation(value="委托公示-待办列表", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="委托公示-待办列表")
    public void findEntrustTodo(NoticeBoardParam param, PageParam pageParam){
        log.info("开始查询委托公示-待办列表，查询条件是：{}", param);
        param.setBusinessType(Constant.BusinessCode.LINSHI);
        param.setTableOrder("BCX56");
        param.setBusinessType(Constant.BusinessCode.LINSHI);
        Page page = noticeBoardReadService.findEntrustTodo(param,pageParam, getCurUserAccount());
        this.setPageBean(page);
        log.info("委托公示-待办列表查询结果，结果是：{}", page);
    }


    @PostMapping("findEntrustFinish")
    @ApiOperation(value="委托公示-已办列表", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="委托公示-待办列表")
    public void findEntrustFinish(NoticeBoardParam param, PageParam pageParam){
        log.info("开始查询委托公示-已办列表，查询条件是：{}", param);
        param.setBusinessType(Constant.BusinessCode.LINSHI);
        param.setTableOrder("BCX56");
        Page page = noticeBoardReadService.findEntrustFinish(param,pageParam, getCurUserAccount());
        this.setPageBean(page);
        log.info("委托公示-已办列表查询结果，结果是：{}", page);
    }


    @PostMapping("clearRedisKey")
    @ApiOperation(value="清除redis的缓存", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="清除redis的缓存")
    public void clearRedisKey(String batchId){
        log.info("清除redis的缓存，查询条件是：{}", batchId);
        //param.setBusinessType(Constant.BusinessCode.LINSHI);
        Boolean aBoolean = tempNoticeBoardService.deleteRedisKey(batchId);
        this.setData(aBoolean);
        log.info("清除redis的缓存，结果是：{}", aBoolean);
    }


    @PostMapping("printNoticeBoardTown")
    @ApiOperation(value="打印公示名单-乡镇", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="打印公示名单-乡镇")
    public void printNoticeBoardTown(OrderListSearchParam param){
        log.info("开始查询打印公示名单-乡镇，批次号是：{}", param);
        Map<String, Object> rstMap = tempNoticeBoardService.printNoticeBoardTown(param);
        setData("data", rstMap);
        log.info("查询打印公示名单-乡镇结束，结果是：{}", rstMap);
    }


    @PostMapping("checkBatchStateByConfirm")
    @ApiOperation(value="判断公示是否可以编辑对象", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,notes="判断公示是否可以编辑对象")
    public void checkBatchStateByConfirm(@V("notnull") String batchId,String type){
        log.info("判断公示是否可以编辑对象，批次号是：{}", batchId);
        int rst = noticeBoardReadService.checkNoticeOpera(batchId,"1", type);
        setData(rst);
        log.info("判断公示是否可以编辑对象，结果是：{}", rst);
    }


    private String packageRstMsg(Map<String, List<String>> rstMap){
        if(rstMap.containsKey("noOperation") == false && rstMap.containsKey("noObject") == false && rstMap.containsKey("success") == true){
            return "操作成功";
        }
        if(rstMap.containsKey("noOperation") == false && rstMap.containsKey("noObject") == false && rstMap.containsKey("fail") == true){
            return "操作失败";
        }
        StringBuffer rstMsg = new StringBuffer();
        if(rstMap.containsKey("noOperation")){
            rstMsg.append("批次【").append(String.join("," , rstMap.get("noOperation"))).append("】状态不对/已经过了开始时间，不可以被操作");
        }
        if(rstMap.containsKey("noObject")){
            rstMsg.append("批次【").append(String.join("," , rstMap.get("noObject"))).append("】没有对象，不可以被操作");
        }
        if(rstMap.containsKey("success")){
            rstMsg.append("批次【").append(String.join("," , rstMap.get("success"))).append("】成功");
        }
        if(rstMap.containsKey("fail")){
            rstMsg.append("批次【").append(String.join("," , rstMap.get("fail"))).append("】失败");
        }
        return rstMsg.toString();
    }
}
